package com.tanchengjin.admin.modules.blog.controller.api.v1.auth;

import com.tanchengjin.admin.config.AdminConfig;
import com.tanchengjin.admin.model.dao.UserMapper;
import com.tanchengjin.admin.model.pojo.User;
import com.tanchengjin.admin.modules.blog.config.ApiConfig;
import com.tanchengjin.admin.modules.blog.config.jwt.JWTSuccessResponse;
import com.tanchengjin.admin.modules.blog.service.UserService;
import com.tanchengjin.admin.modules.blog.utils.JWTUtil;
import com.tanchengjin.admin.modules.blog.utils.ServerResponse;
import com.tanchengjin.admin.modules.blog.validations.MiniProgramAuthenticationValidate;
import com.tanchengjin.admin.modules.blog.vo.MiniProgramVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;

@Api(tags = "用户认证")
@RestController
public class ApiAuthenticationController {
    @Autowired
    private AdminConfig adminConfig;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private ApiConfig apiConfig;

    @Autowired
    private UserService userService;

    @Value("${app.miniprogram.appid}")
    private String appid;
    @Value("${app.miniprogram.secret}")
    private String secret;

    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "${app.api.prefix}/auth/login", method = RequestMethod.POST)
    public ServerResponse login(String username, String password) {
        if (username == null || password == null || username.isEmpty() || password.isEmpty()) {
            return ServerResponse.responseWithFailureMessage("用户名密码不允许为空");
        }
        User user = userMapper.findByUsername(username);
        if (user == null) {
            return ServerResponse.responseWithFailureMessage("认证失败，请重试");
        }

        if (!passwordEncoder.matches(password, user.getPassword())) {
            return ServerResponse.responseWithFailureMessage("密码错误");
        }

        return ServerResponse.responseWithSuccess(JWTSuccessResponse.response("access_token", "type", "re", 1000));
    }

    @ApiOperation(value = "用户注册")
    @RequestMapping(value = "${app.api.prefix}/auth/register", method = RequestMethod.POST)
    public Object register(String username, String password, HttpServletRequest request) {
        if (username.isEmpty() || password.isEmpty()) {
            return ServerResponse.responseWithFailureMessage("用户名密码不允许为空");
        }
        User byUsername = userMapper.findByUsername(username);
        if (byUsername != null) return ServerResponse.responseWithFailureMessage("用户名已存在");
        //数据入库
        User user = new User();
        user.setName(username);
        user.setPassword(passwordEncoder.encode(password));
        int i = userMapper.insertSelective(user);
        if (i >= 1) {
            //获取令牌过期时间
            Date ate = new Date((System.currentTimeMillis() / 1000) + apiConfig.getJwtAccessTokenExpireTime());
            Date rte = new Date((System.currentTimeMillis() / 1000) + apiConfig.getJwtRefreshTokenExpireTime());
            String token = JWTUtil.sign(apiConfig.getJwtSecret(), user.getUsername(), user.getId(), ate);
            String refreshToken = JWTUtil.get_refresh_token(apiConfig.getJwtSecret(), user.getUsername(), user.getId(), rte);
            return JWTSuccessResponse.response(token, apiConfig.getJwtType(), refreshToken, ate.getTime());
        }
        return ServerResponse.responseWithFailureMessage("注册失败,请重试!");
    }

    /**
     * 用于小程序登录
     * 兼容老接口
     */
    @ApiOperation(value = "小程序用户登录")
    @RequestMapping(value = "${app.api.prefix}/authorization/miniProgram", method = RequestMethod.POST)
    public MiniProgramVO loginByMiniProgram(@RequestBody @Valid MiniProgramAuthenticationValidate validate) {
        MiniProgramVO miniProgramVO = userService.miniProgramAuth(validate);
        return miniProgramVO;
    }
}
